from django.http import JsonResponse
from django.conf import settings
from user.models import User
import jwt


def login_verify(func):
    def login_fun(request, *args, **kwargs):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')
            print(token)
        except AttributeError:
            return JsonResponse({"code": 401, "message": "No authenticate header"})

        try:
            dict = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
            openid = dict.get('openid')
        except jwt.ExpiredSignatureError:
            return JsonResponse({"status_code": 401, "message": "Token expired"})
        except jwt.InvalidTokenError:
            return JsonResponse({"status_code": 401, "message": "Invalid token"})
        except Exception as e:
            print(e)
            return JsonResponse({"status_code": 401, "message": "Can not get user object"})
        try:
            User.objects.get(openid=openid)
        except Exception as e:
            return JsonResponse({"status_code": 401, "message": "User Does not exist"})

        return func(request, *args, **kwargs)

    return login_fun
